package com.hcss.core.mvc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.hcss.core.common.permissions.model.UserInfo;
import com.hcss.core.mvc.page.Pager;
import com.hcss.core.util.SysDictionary;



/** 
 * @ClassName: BaseDao 
 * @Description: 用于DAO的基类
 * @author lvfang
 * @date 2013-3-26 上午10:03:37 
 *  
 */
@Repository("baseDao")
public class BaseDao{
	public final Logger logger  =  Logger.getLogger(getClass());
	@Autowired
	public JdbcTemplate jdbcTemplate;
	
	@Autowired
	public HibernateTemplate hibernateTemplate;
	
	@Autowired
	public SessionFactory sessionFactory;
	
	
	public Session getHibernateSession(){
		return sessionFactory.getCurrentSession();
	}
	/** 
	* @Title: getPageList 
	* @Description: TODO 
	* @param sql sql语句
	* @param page 当前分页对象（包括分页参数）
	* @param rowMapper 数据行映射对象
	* @return Pager
	* @throws 
	*/ 
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Pager getPageList(String sql,Pager page,RowMapper rowMapper) throws Exception{
		int queryForSize = jdbcTemplate.query(sql,rowMapper).size();
		StringBuffer sb = new StringBuffer(sql);
		if(!"".equals(page.getOrder()) && page.getOrder() != null){
			sb.append(" order by "+page.getSort() +" "+page.getOrder());
		}
		
		sb.append(" LIMIT ");
		sb.append(page.getStartRow());
		sb.append(", ");
		sb.append(page.getPageSize());
		
		List query = jdbcTemplate.query(sb.toString(),rowMapper);
		List<?> dataList = query;
		page.setDataList(dataList);
		page.setTotalRows(queryForSize);
		return page;
	}
	
	/** 
	* @Title: getPageListByTotal 合计行 
	* @Description: TODO 
	* @param sql sql语句
	* @param page 当前分页对象（包括分页参数）
	* @param rowMapper 数据行映射对象
	* @return Pager
	* @throws 
	*/ 
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public Pager getPageListByTotal(String sql,String sqlTotal,Pager page,RowMapper rowMapper,
			RowMapper rowMapperTotal) throws Exception{
		int queryForSize = jdbcTemplate.query(sql,rowMapper).size();
		StringBuffer sb = new StringBuffer(sql);
		if(!"".equals(page.getOrder()) && page.getOrder() != null){
			sb.append(" order by "+page.getSort() +" "+page.getOrder());
		}
		
		sb.append(" LIMIT ");
		sb.append(page.getStartRow());
		sb.append(", ");
		sb.append(page.getPageSize());
		
		List query = jdbcTemplate.query(sb.toString(),rowMapper);
		List footerList = jdbcTemplate.query(sqlTotal,rowMapperTotal);
		List<?> dataList = query;
		page.setDataList(dataList);
		page.setTotalRows(queryForSize);
		page.setFooterList(footerList);
		return page;
	}
	/**
	 * 获取用户ID
	 * @return
	 */
	protected UserInfo getUserInfo(){
		HttpServletRequest request = ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest();
		return (UserInfo)request.getSession().getAttribute(SysDictionary.LOGIN_USERINFO);
	}
	
	/**
     * 新增返回主键ID
     * 
     * @param sql
     * @param params
     * @return
     */
    public int insertSelective(final String sql, final Object[] params) {
        KeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection conn) throws SQLException {
                PreparedStatement ps = conn.prepareStatement(sql.toString(), Statement.RETURN_GENERATED_KEYS);
                for (int i = 0; i < params.length; i++) {
                	ps.setObject((i + 1), params[i]);
                }
                return ps;
            }
        }, keyHolder);
        return keyHolder.getKey().intValue();
    }

}
